<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>采購訂單</span><span v-if="updateStatus">{{ code }}</span>
        <el-button v-if="updateStatus" class="buttonA" type="warning" @click="exportExcel">導出Excel</el-button>
        <el-button class="buttonC" type="success" @click="onSubmit">保存采購單</el-button>
      </div>
      <el-form ref="form" :model="form" label-width="auto">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供應商">
              <el-select
                v-model="form.vendorId"
                placeholder="請輸入關鍵字"
                :loading="loading"
                style="width: 200px"
                filterable
                clearable
                @change="lastTime(form.vendorId)"
              >
                <el-option
                  v-for="item in list"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上次入倉日期">
              <el-input v-model="form.lastTime" :disabled="true" style="width: 200px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="送貨地址">
              <el-select
                v-model="form.deliveryAddress"
                placeholder="請輸入地址"
                :loading="loading"
                style="width: 300px"
                filterable
                clearable
              >
                <el-option
                  v-for="(item,index) in depotAddress"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采購單描述">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="1"
                style="width: 500px"
                placeholder="請輸入内容"
              />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header" class="clearfix">
        <span>采購商品明細</span>
        <el-button class="buttonB" type="primary" @click="choose">
          添加商品
        </el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        height="410"
      >
        <el-table-column
          prop="nameCn"
          label="產品名稱"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.nameCn }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sku"
          label="產品編號"
        >
          <template slot-scope="scope">
            {{ scope.row.product.sku }}
          </template>
        </el-table-column>
        <el-table-column
          prop="bsl"
          label="bsl"
        >
          <template slot-scope="scope">
            {{ scope.row.product.bsl }}
          </template>
        </el-table-column>
        <el-table-column
          prop="bsl"
          label="前次成本"
        >
          <template slot-scope="scope">
            {{ scope.row.product.bsl }}
          </template>
        </el-table-column>
        <el-table-column
          prop="outStock"
          label="缺貨數量"
        >
          <template slot-scope="scope">
            {{ scope.row.product.outStock }}
          </template>
        </el-table-column>
        <el-table-column
          prop="upc"
          label="條形碼"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.upc }}</span></template>
        </el-table-column>
        <el-table-column
          prop="productCategory"
          label="產品種類"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.productCategory.nameCn }}</span></template>
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="采購數量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.quantity" />
          </template>
        </el-table-column>
        <el-table-column
          prop="unitQuantity"
          label="單位數量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.unitQuantity" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column
          prop="productCategory"
          label="采購單位"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.unit" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="備注"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" placeholder="备注" />
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="deleteRow(scope.$index, tableData)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <choose-product ref="chooseProduct" :select="selectData" @childNotify="childNotify" />
  </div>
</template>

<script>
import api from '@/api/erp/purchase'
import vendorApi from '@/api/cms/vendor'
import chooseProduct from '@/components/product/index'
import Vue from 'vue'
import router from '@/router/routers'
import store from '@/store'
import { mapGetters } from 'vuex'
import depotApi from '@/api/wms/depot'
import { downloadFile } from '@/utils'

export default {
  name: 'CreatPurchase',
  components: { chooseProduct },
  props: {
    model: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      deptoOptions: [],
      amountNumber: 0,
      priceCheckList: [],
      allNum: 0,
      // tagState: false,
      tableData: [],
      selectData: [],
      vendorOptions: [],
      newArr: [],
      arrId: [],
      list: [],
      depotAddress: [],
      loading: false,
      updateStatus: false,
      code: '',
      form: {
        deliveryAddress: '',
        depotId: '',
        approveStatus: '',
        description: '',
        id: '',
        paymentStatus: '',
        receiveStatus: '',
        createTime: '',
        vendorId: '',
        lastTime: '',
        purchaseItems: []
        // shipping: 0,
        // otherFee: 0
      },
      tempRoute: {}
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  watch: {
    '$route': {
      handler(route) {
        if (this.$route.params.vendorId) {
          this.form.vendorId = this.$route.params.vendorId
        }
        if (this.$route.params.products) {
          const products = JSON.parse(JSON.stringify(this.$route.params.products).replace(/productName/g, 'nameCn'))
          products.forEach((item, index) => {
            if (!this.arrId.includes(item.productId)) {
              this.tableData.push({ product: item })
              this.arrId.push(item.productId)
            }
          })
        }
      },
      deep: true
    }
  },
  mounted() {
    depotApi.page({ 'depotType': '1' }).then(res => {
      for (let i = 0; i < res.data.rows.length; i++) {
        this.deptoOptions.push({ label: res.data.rows[i].name, value: res.data.rows[i].id })
      }
    })
  },
  created() {
    this.getVendor()
    this.getDepotAddress()
    var date = new Date()
    this.form.createTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
      date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
    const id = this.$route.params.id
    if (id === 'add') {
      this.setTitle('新增采购单')
      if (this.$route.params.vendorId) {
        this.form.vendorId = this.$route.params.vendorId
      }
      if (this.$route.params.products) {
        const products = JSON.parse(JSON.stringify(this.$route.params.products).replace(/productName/g, 'nameCn'))
        products.forEach((item, index) => {
          if (!this.arrId.includes(item.productId)) {
            this.tableData.push({ product: item })
            this.arrId.push(item.productId)
          }
        })
      }
    } else {
      api.getOne(id).then(res => {
        const purchaseItem = res.data
        this.form.deliveryAddress = purchaseItem.deliveryAddress
        this.form.description = purchaseItem.description
        this.code = purchaseItem.code
        this.form.createTime = purchaseItem.createTime
        this.form.vendorId = purchaseItem.vendorId
        this.form.lastTime = purchaseItem.lastTime
        this.form.depotId = purchaseItem.depotId
        this.tableData = purchaseItem.purchaseItems
        this.updateStatus = true
        this.setTitle('修改采购单')
        this.selectData = purchaseItem.purchaseItems
      })
    }
  },
  methods: {
    exportExcel() {
      const id = this.$route.params.id
      api.exportExcel({ id: id }).then((res) => {
        downloadFile(res, '采购单', 'xlsx')
        this.$message.success('导出成功')
      })
    },
    getDepotAddress() {
      depotApi.getDepotAddress().then(res => {
        if (res.code === 0) {
          this.depotAddress = res.data
          if (this.depotAddress.length > 0) {
            this.form.deliveryAddress = this.depotAddress[0]
          }
        }
      })
    },
    getVendor() {
      vendorApi.getAll().then(res => {
        for (let i = 0; i < res.data.length; i++) {
          this.list.push({ label: res.data[i].name, value: res.data[i].id })
        }
      })
    },
    setTitle(title) {
      Vue.nextTick(() => {
        const routeTitle = Object.assign(Object.assign({}, router.currentRoute), { title })
        store.dispatch('tagsView/updateVisitedView', routeTitle)
        document.title = title
      })
    },
    childNotify(params) {
      if (params.length === 0) {
        this.$message.error('请选择商品')
      } else {
        const productIdArr = this.tableData.map(item => {
          return item.product.sku
        })
        for (var item of params) {
          if (this.arrId.indexOf(item.product.id) === -1) {
            this.arrId.push(item.product.id)
            if (!productIdArr.includes(item.sku)) {
              this.tableData.push(item)
            }
          }
        }
        this.$refs.chooseProduct.close()
        this.$refs.chooseProduct.refresh()
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    onSubmit() {
      if (this.form === null) {
        this.$message.error('请填写采购单')
        return
      }
      if (this.tableData.length === 0) {
        this.$message.error('请填写采购单详情')
        return
      }
      this.form.id = this.$route.params.id
      const addEditData = []
      for (let i = 0; i < this.tableData.length; i++) {
        addEditData.push({
          'productId': this.tableData[i].product.id,
          'id': this.form.id === 'add' ? null : this.tableData[i].id,
          'unitQuantity': this.tableData[i].unitQuantity,
          'remark': this.tableData[i].remark,
          'unit': this.tableData[i].unit,
          'quantity': this.tableData[i].quantity
        })
      }
      this.form.purchaseItems = addEditData
      if (this.form.id === 'add') {
        this.form.id = null
        api.add(this.form).then(() => {
          this.tableData = []
          this.form = {}
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1)
        })
      } else {
        api.edit(this.form).then(() => {
          this.tableData = []
          this.form = {}
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1)
        })
      }
    },
    choose() {
      this.$refs.chooseProduct.open()
    },
    lastTime(id) {
      if (id) {
        vendorApi.getOne(id).then(res => {
          this.form.lastTime = res.data.lastTime
        })
      } else {
        this.form.lastTime = null
      }
    }
  }
}
</script>

<style scoped>
.buttonA {
  right: 15%;
  position: absolute;
}

.buttonC {
  right: 5%;
  position: absolute;
}

.buttonB {
  right: 5%;
  position: absolute;
}

.tableImg {
  width: 50px;
  margin-right: 6px;
  float: left;
}

.productInfo span {
  display: block;
  line-height: 16px;
}

.totalRow {
  text-align: right;
  color: gray;
}

.el-popover.my-popover {
  padding: 20px 10px;
  position: absolute;
  top: 50px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix {
  height: 20px;
}

[v-cloak] {
  display: none;
}
</style>
